package oj_leetcode;

public class ZigZagConversion {

    public String convert(String s, int numRows) {
        if (numRows == 1) {
            return s;
        }
        int lastIndex = s.length() - 1;
        StringBuilder result = new StringBuilder();
        for (int m = 1; m <= numRows; m++) {
            int k = 0;
            int currIndex = getIndexOfBeginEndRow(k, numRows, m);
            while (currIndex <= lastIndex) {
                result.append(s.charAt(currIndex));
                if (m != 1 && m != numRows) {
                    int midIndex = getIndexOfMiddleRow(k, numRows, m);
                    if (midIndex <= lastIndex) {
                        result.append(s.charAt(midIndex));
                    }
                }
                k++;
                currIndex = getIndexOfBeginEndRow(k, numRows, m);
            }
        }
        return result.toString();
    }


    /**
     * N行数据，第m行的第k次迭代
     *
     * @param k
     * @param N
     * @param m
     * @return
     */
    private int getIndexOfBeginEndRow(int k, int N, int m) {
        return k * (2 * N - 2) + m - 1;
    }


    private int getIndexOfMiddleRow(int k, int N, int m) {
        return k * (2 * N - 2) + (2 * N - m) - 1;
    }


    public static void main(String[] args) {
        System.out.println(new ZigZagConversion().convert("PAYPALISHIRING", 1));
    }
}
